package com.tju.resource.oauth.controller.tb;

import com.tju.resource.annotation.Log;
import com.tju.resource.model.TbSupplier;
import com.tju.resource.business.tb_supplier.TbSupplierService;
import com.tju.resource.result.Result;
import com.tju.resource.result.ResultEnum;
import com.tju.resource.result.ResultUtil;
import com.tju.resource.tool.enum_utils.FunctionType;
import com.tju.resource.tool.tool.ClientParameters;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.Objects;

@RestController
public class TbSupplierController {
    private final String prefix = "supplier";

    @Autowired
    TbSupplierService tbSupplierService;

    /**
     * 查询全部供应商信息
     *
     * @param parameters
     * @return
     */
    @PreAuthorize("hasAuthority('sys:spClient:supplier:list')")
    @PostMapping(prefix + "/getSupplier")
    @Log(type = FunctionType.List)
    public Result<Object> getSupplier(@RequestBody ClientParameters parameters) {
        return tbSupplierService.getSupplier(parameters);
    }

    /**
     * 添加供应商信息
     *
     * @param tbSupplier
     * @return
     */
    @PreAuthorize("hasAuthority('sys:spClient:supplier:add')")
    @PostMapping(prefix + "/addSupplier")
    @Log(type = FunctionType.Add)
    public Result<Object> addSupplier(@Valid @RequestBody TbSupplier tbSupplier, BindingResult result) {
        if (result.hasErrors()) {
            return ResultUtil.error(ResultEnum.UNKONW_ERROR, Objects.requireNonNull(result.getFieldError()).getDefaultMessage());
        } else
            return tbSupplierService.addSupplier(tbSupplier);
    }

    /**
     * 删除供应商信息
     *
     * @param tbSupplier
     * @return
     */
    @PreAuthorize("hasAuthority('sys:spClient:supplier:delete')")
    @PostMapping(prefix + "/delSupplier")
    @Log(type = FunctionType.Delete)
    public Result<Object> delSupplier(@RequestBody TbSupplier tbSupplier) {
        return tbSupplierService.delSupplier(tbSupplier);
    }

    /**
     * 修改供应商信息
     *
     * @param tbSupplier
     * @return
     */
    @PreAuthorize("hasAuthority('sys:spClient:supplier:edit')")
    @PostMapping(prefix + "/updSupplier")
    @Log(type = FunctionType.Modify)
    public Result<Object> updSupplier(@Valid @RequestBody TbSupplier tbSupplier, BindingResult result) {
        if (result.hasErrors()) {
            return ResultUtil.error(ResultEnum.UNKONW_ERROR, Objects.requireNonNull(result.getFieldError()).getDefaultMessage());
        } else
            return tbSupplierService.updSupplier(tbSupplier);
    }
}
